package com.soo.hoo.admin.config;


import com.alibaba.fastjson2.filter.NameFilter;
import com.alibaba.fastjson2.filter.ValueFilter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 * fastjson2全局配置
 * </p>
 *
 * @author 杨燚
 * @since 2022-05-12
 */
@Configuration
public class FastJson2Config {


    @Bean
    public HttpMessageConverters httpMessageConverters() {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();

        // 添加过滤器
        config.setWriterFilters(
                // 对象的字段过滤器，不做任何处理，但必须加上，不然序列化后的对象字段名会变为null
                (NameFilter) (source, name, value) -> name,
                // 对象的值过滤器，把Long类型的值转为字符，解决前端精度丢失问题
                (ValueFilter) (source, name, value) -> {
                    if (value instanceof Long) {
                        return value.toString();
                    }
                    return value;
                }
        );

        // 设置全局日期格式
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");

        converter.setDefaultCharset(StandardCharsets.UTF_8);
        converter.setFastJsonConfig(config);

        return new HttpMessageConverters(converter);
    }

}
